import chalk from 'chalk';
import { exec } from 'child_process';
import inquirer from 'inquirer';
import path from 'path';
import modifyPackJson from './init-tpl/index';
import { download } from './utils/download-git-project';

const log = console.log;

const tpls = [
  {
    name: 'React + TypeScript + Vite',
    url: 'https://gitlab-front.ebonex.io/api/v4/projects/350/repository/archive.zip',
  },
];

export default function init(tplName: string) {
  start(tplName);
}

function start(tplName: string) {
  if (tplName) {
    isTransferQuestion(tplName);
    return;
  }
  inquirer
    .prompt([
      {
        type: 'list',
        name: 'tplName',
        message: '请选择模板:',
        prefix: '➜',
        choices: tpls?.map((v) => v?.name),
      },
    ])
    .then((answers) => {
      isTransferQuestion(answers.tplName);
    });
}

function question(url: string) {
  const questions = [
    {
      type: 'input',
      name: 'projectName',
      prefix: '➜',
      message: '项目名称:',
      validate: function (input) {
        if (input.trim() === '') {
          return '项目名称不能为空，请重新输入';
        }
        return true;
      },
    },
    {
      type: 'input',
      name: 'version',
      prefix: '➜',
      message: '版本号:',
    },
    {
      type: 'input',
      name: 'mail',
      prefix: '➜',
      message: '邮箱:',
    },
    {
      type: 'list',
      name: 'bag',
      prefix: '➜',
      message: '包管理源:',
      choices: ['npm', 'yarn', 'pnpm'],
    },
  ];

  inquirer
    .prompt(questions)
    .then((answers) => {
      downLoad(answers, url);
    })
    .catch((error) => {
      console.error('Error:', error);
    });
}

function downLoad(answers: any, url: string) {
  exec(`mkdir ${answers?.projectName}`, (error, stdout, stderr) => {
    if (error) {
      console.error(`mkdir eror: ${error.message}`);
      return;
    }
    if (stderr) {
      console.error(`mkdir error: ${stderr}`);
      return;
    }
    progress(answers, url);
  });
}

function isTransferQuestion(tplName: string) {
  const n = tpls?.filter((n) => n?.name === tplName)?.[0];
  if (n) {
    question(n?.url);
  } else {
    log(chalk.red('暂不支持, 请等待后续开发提供...'));
  }
}

async function progress(answers, url) {
  const pathRoot = path.join(process.cwd(), answers?.projectName || '');
  await download({ dir: pathRoot, url });
  modifyPackJson({
    packageManager: answers?.bag,
    projectInfo: answers,
  });
  // const cloneProcess = exec(
  //   `git clone --progress ${url} ${answers?.projectName}`,
  // );
  // cloneProcess.on('close', (code) => {
  //   if (code === 0) {
  //     modifyPackJson({
  //       packageManager: answers?.bag,
  //       projectInfo: answers,
  //     });
  //   } else {
  //     console.error('Clone failed with code', code);
  //   }
  // });
}
